﻿using System;
using System.Collections.Generic;
using System.Text;
using FlubuCore.TaskGenerator.Models;
using FlubuCore.TaskGenerator.Models.Extensions;
using Microsoft.CodeAnalysis;
using Scripty.Core;

namespace FlubuCore.TaskGenerator
{
    public class FlubuConsoleTaskGenerator : TaskGeneratorBase
    {
        private readonly ScriptContext _context;

        public FlubuConsoleTaskGenerator(ScriptContext context)
        {
            _context = context;
        }

        public void GenerateCommandHints(List<Task> tasks, string id)
        {
            

            _context.Output[$"{id}Commands.cs"]
                .WriteLine($@"
//-----------------------------------------------------------------------
// <auto-generated />
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;

namespace FlubuCore.Infrastructure.Terminal.Commands
{{
    public static class {id}Commands
    {{  
        {WriteSupportedExternalProcesses(tasks)}{Environment.NewLine}{Environment.NewLine}     
        {WriteCommandHints(id, tasks)}
    }}
}}
");
        }

        public string WriteSupportedExternalProcesses(List<Task> tasks)
        {
            string dictionary = $@"public static Dictionary<string, Type> SupportedExternalProcesses = new Dictionary<string, Type>()
    {{{Environment.NewLine}";

            foreach (var task in tasks)
            {
                dictionary = $@"{dictionary}{{ ""{task.ExecutablePath} {task.Constructor.Arguments[0].ArgumentKey}"", typeof({task.TaskName}) }},{Environment.NewLine}";
            }

            dictionary = $"{dictionary}}};";
            
            return dictionary;
        }

        public string WriteCommandHints(string rootCommand, List<Task> tasks)
        {
            string commandHints = $@"public static KeyValuePair<string, IReadOnlyCollection<Hint>> GitCommandHints {{ get; }} = new KeyValuePair<string, IReadOnlyCollection<Hint>>(""{rootCommand}"", new List<Hint>()
              {{{Environment.NewLine}";

            foreach (var task in tasks)
            {
                commandHints = $@"{commandHints} new Hint {{ Name = ""{task.Constructor.Arguments[0].ArgumentKey}"", Help = ""{task.TaskDescription}"" }},{Environment.NewLine}";
            }

            commandHints = $"{commandHints}}});";

            return commandHints;
        }
    }
}
